package com.wd.cloud.applet.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wd.cloud.applet.common.RetailersSecurityMsgUtils;
import com.wd.cloud.applet.common.RetailersSecurityUtils;
import com.wd.cloud.applet.common.constant.dataverify.Constant;
import com.wd.cloud.applet.common.exception.CustomException;
import com.wd.cloud.applet.config.CustomListResultConfig;
import com.wd.cloud.applet.config.ModelMapperConfig;
import com.wd.cloud.applet.config.MybatisPlusPageConfig;
import com.wd.cloud.applet.entity.bo.SysUserRoleInfoBO.SysUserRoleInfoListBO;
import com.wd.cloud.applet.entity.bo.SysUserRoleInfoBO.SysUserRoleInfoSaveBO;
import com.wd.cloud.applet.entity.bo.SysUsersInfoBO.SysUsersInfoListBO;
import com.wd.cloud.applet.entity.bo.SysUsersInfoBO.SysUsersInfoLoginBO;
import com.wd.cloud.applet.entity.bo.SysUsersInfoBO.SysUsersInfoSaveBO;
import com.wd.cloud.applet.entity.commons.RequestPrimaryKeyModel;
import com.wd.cloud.applet.entity.dto.SysUserRoleInfoModel;
import com.wd.cloud.applet.entity.dto.SysUsersInfoModel;
import com.wd.cloud.applet.entity.vo.SysMenuInfoVO.SysMenuInfoListVO;
import com.wd.cloud.applet.entity.vo.SysUserRoleInfoVO.SysUserRoleInfoListVO;
import com.wd.cloud.applet.entity.vo.SysUsersInfoVO.SysUsersInfoKeyVO;
import com.wd.cloud.applet.entity.vo.SysUsersInfoVO.SysUsersInfoListVO;
import com.wd.cloud.applet.entity.vo.SysUsersInfoVO.SysUsersInfoLoginVO;
import com.wd.cloud.applet.mapper.SysMenuInfoMapper;
import com.wd.cloud.applet.mapper.SysUserRoleInfoMapper;
import com.wd.cloud.applet.mapper.SysUsersInfoMapper;
import com.wd.cloud.applet.service.ISysUserRoleInfoService;
import com.wd.cloud.applet.service.ISysUsersInfoService;
import com.wd.cloud.applet.utils.HelperUtils;
import com.wd.cloud.applet.utils.cache.RedisUtil;
import com.wd.cloud.applet.utils.string.StringUtils;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;

/**
* Description: [用户表服务实现]
* Created on 2023年04月21日
* @author  <a href="mailto: 987707681@qq.com">hjx</a>
* @version 1.0
* Copyright (c) 2023年 代码生成器
*/
@Service
public class SysUsersInfoServiceImpl extends ServiceImpl<SysUsersInfoMapper, SysUsersInfoModel> implements ISysUsersInfoService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private SysUsersInfoMapper appletMapper;
    @Resource
    private RetailersSecurityMsgUtils securityMsgUtils;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ISysUserRoleInfoService roleInfoService;
    @Resource
    private SysUserRoleInfoMapper roleInfoMapper;
    @Resource
    private SysMenuInfoMapper menuInfoMapper;
    /**
     * 根据主键ID删除数据（逻辑删除）
     *
     * @param params
     * @return
     */
    @Override
    public int deleteByPrimaryKey(RequestPrimaryKeyModel params) {
        if (StringUtils.isNullOrTrimEmpty(params.getId())) {
            throw new CustomException("请选择需要删除的数据", 100);
        }
        SysUsersInfoModel model = appletMapper.selectById(params.getId());
        if (model == null) {
            throw new CustomException("删除的数据不存在", 100);
        }
        model.setDeleteMark(Constant.SUCCESS_DELETE);
        return appletMapper.updateById(model);
    }

    /**
     * 新增数据
     *
     * @param params
     * @return
     */
    @Override
    public int insertSelective(SysUsersInfoSaveBO params) {
        SysUsersInfoModel model = ModelMapperConfig.mapTo(SysUsersInfoModel.class, params);
        model.setId(HelperUtils.getUuid());
        model.setCreateTime(new Date());
        return appletMapper.insert(model);
    }

    /**
     * 新增或修改
     *
     * @param params
     * @return
     */
    @Override
    public int save(SysUsersInfoSaveBO params) {
        SysUsersInfoModel model = ModelMapperConfig.mapTo(SysUsersInfoModel.class, params);
        if (model != null) {
            if (model.getId() == null || model.getId().isEmpty()) {
                model.setId(HelperUtils.getUuid());
                model.setCreateTime(new Date());
                appletMapper.insert(model);
            } else {
                appletMapper.updateById(model);
            }
            RequestPrimaryKeyModel primaryKeyModel=new RequestPrimaryKeyModel();
            primaryKeyModel.setId(model.getId());
            roleInfoService.deleteByPrimaryKey(primaryKeyModel);
            List<SysUserRoleInfoModel> roleInfoModels = new ArrayList<>();
            for (String str : params.getRole()) {
                SysUserRoleInfoModel roleInfoModel = new SysUserRoleInfoModel();
                roleInfoModel.setRoleId(str);
                roleInfoModel.setUserId(model.getId());
                roleInfoModel.setId(HelperUtils.getUuid());
                roleInfoModels.add(roleInfoModel);
            }
            roleInfoService.saveBatch(roleInfoModels);
            return 1;
        }
        return 0;
    }

    /**
     * 分页获取数据列表
     *
     * @param params
     * @return
     */
    @Override
    public CustomListResultConfig<SysUsersInfoListVO> selectByPageList(SysUsersInfoListBO params) {
        LambdaQueryWrapper<SysUsersInfoModel> userLambdaQueryWrapper = Wrappers.lambdaQuery();
        userLambdaQueryWrapper.orderByDesc(SysUsersInfoModel::getCreateTime);
        Page<SysUsersInfoModel> page = new Page<>(params.getPage(), params.getLimit());
        IPage<SysUsersInfoModel> entityIPage =
            appletMapper.selectPage(page, userLambdaQueryWrapper);
        CustomListResultConfig<SysUsersInfoListVO> responseDtoList =
            MybatisPlusPageConfig.toPageResult(entityIPage, SysUsersInfoListVO.class);
        if (responseDtoList.getList().size() <= 0) {
            throw new CustomException("查无数据", 102);
        }
        return responseDtoList;
    }

    /**
     * 根据主键id获取实体
     *
     * @param
     * @return
     */
    @Override
    public SysUsersInfoKeyVO userInfo() {
        SysUsersInfoKeyVO sysUsersInfoLoginVO = securityMsgUtils.getLoginUserInfo();
        SysUserRoleInfoListBO infoListBO = new SysUserRoleInfoListBO();
        infoListBO.setId(sysUsersInfoLoginVO.getId());
        List<SysUserRoleInfoListVO> roleInfoListVOList =
            roleInfoMapper.queryUserRoleTable(infoListBO);
        List<String> rolesList = new ArrayList<>();
        List<String> buttonList = new ArrayList<>();
        for (SysUserRoleInfoListVO infoListVO : roleInfoListVOList) {
            rolesList.add(infoListVO.getRval());
            RequestPrimaryKeyModel keyModel = new RequestPrimaryKeyModel();
            keyModel.setId(infoListVO.getRoleId());
            List<SysMenuInfoListVO> sysMenuInfoListVOList = menuInfoMapper.queryMuchTable(keyModel);
            for (SysMenuInfoListVO menuInfoListVO : sysMenuInfoListVOList) {
                buttonList.add(menuInfoListVO.getRval());
            }
        }
        sysUsersInfoLoginVO.setButton(buttonList);
        sysUsersInfoLoginVO.setRoles(rolesList);
        return sysUsersInfoLoginVO;
    }
    /**
     * 根据主键id获取实体
     *
     * @param params
     * @return
     */
    @Override
    public SysUsersInfoLoginVO login(SysUsersInfoLoginBO params) {
        SysUsersInfoLoginVO usersInfoLoginVO=new SysUsersInfoLoginVO();
        String accessToken = securityMsgUtils.getUserId(params);
        if (StringUtils.isNotEmpty(accessToken)) {
            usersInfoLoginVO.setToken(accessToken);
            return usersInfoLoginVO;
        }
        LambdaQueryWrapper<SysUsersInfoModel> userLambdaQueryWrapper = Wrappers.lambdaQuery();
        userLambdaQueryWrapper.eq(SysUsersInfoModel::getUserNo,params.getUsername()).eq(SysUsersInfoModel::getUserPassword,params.getPassword());
        SysUsersInfoModel usersInfoModel= appletMapper.selectOne(userLambdaQueryWrapper);
        if (HelperUtils.checkObjAllFieldsIsNull(usersInfoModel)){
            throw new CustomException("用户信息不存在", 100);
        }
        SysUsersInfoKeyVO loginVO = ModelMapperConfig.mapTo(SysUsersInfoKeyVO.class, usersInfoModel);
        accessToken = new String(Base64.getEncoder().encode(JSON.toJSONString(loginVO).getBytes()));
        redisUtil.set(Constant.SHOP_USER_TOKEN_PREFIX_KEY+params.getUsername(), accessToken,100000);
        usersInfoLoginVO.setToken(accessToken);
        return usersInfoLoginVO;
    }

    /**
     * 退出登录
     */
    @Override
    public void logout(){
        securityMsgUtils.logout();
    }
}
